﻿using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Configuration;
using System.Collections;
using System.Data;
using TerraExplorerX;
using Bussiness;

namespace UI
{
    /// <summary>
    /// 点缓冲区查询,获取一个Point的IGeometry，根据缓冲区创建一个Polygon，进行空间分析
    /// SpatialOperator：根据当前的IGeometry和缓冲米数，获取新的IGeometry
    /// </summary>
    public class PointQueryCommand
    {
        public SGWorld sgWorld = new SGWorldClass();
        private ILayer61 layer;
        private double buffer;
        private ListView listView1;        

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(ILayer61 layer,int buffer,ListView list)
        {            
            this.layer = layer;
            this.buffer = buffer;
            this.listView1 = list;

            sgWorld.OnLButtonDown += new _ISGWorld6Events_OnLButtonDownEventHandler(sgWorld_OnLButtonDown);
            //sgWorld.Command.Execute(1012, 5);
            sgWorld.Window.SetInputMode(MouseInputMode.MI_COM_CLIENT);
        }

        private bool sgWorld_OnLButtonDown(int Flags, int X, int Y)
        {
            
            // 使用IWindow6获取鼠标在三维窗口拾取的点
            IWorldPointInfo6 worldPointInfo = sgWorld.Window.PixelToWorld(X, Y);
            // 用来查询的IGeometry。这里是一个点，是用WKT格式创建。
            IGeometry geometry = sgWorld.Creator.GeometryCreator.CreatePointGeometry(string.Format("POINT({0} {1} {2})", worldPointInfo.Position.X, worldPointInfo.Position.Y,worldPointInfo.Position.Altitude));
            
            if (buffer != 0)
            {
               // 如果使用了缓冲区，则用来查询的IGeometry是一个IPolygon，通过对点进行Buffer操作得到 
               geometry = sgWorld.Creator.CreatePolygon(geometry.SpatialOperator.buffer(buffer),
                    Color.Cyan.ToTerraColor(), Color.Transparent.ToTerraColor(), Description: "Buffer").Geometry;   
                sgWorld.ProjectTree.DeleteItem(sgWorld.ProjectTree.FindItem("Buffer")); 
            }
            // 对图层进行空间查询
            IFeatures61 features = layer.ExecuteSpatialQuery(geometry, IntersectionType.IT_WITHIN);
            //因为缓冲区不能识别不同的高度，所以这里添加了该方法来识别楼层
            int selectedIndex=-1;
            IFeature61 selectedFeature;
            double trueElev = worldPointInfo.Position.Altitude-8;
            for (int i = 0; i < features.Count; i++)
            {
                IFeature61 feature = features[i] as IFeature61;
                IFeatureAttributes61 attrs = feature.FeatureAttributes;
                double tempElev = Double.Parse(attrs.GetFeatureAttribute(ConfigurationManager.AppSettings["Z_FieldName"]).Value);
                if (Math.Abs(tempElev - trueElev) < buffer)
                {
                    selectedIndex = i;
                    break;
                }

            }
            if (selectedIndex != -1)
            {
                selectedFeature = features[selectedIndex] as IFeature61;                
                GenerateList(selectedFeature);
            }

            sgWorld.OnLButtonDown -= new _ISGWorld6Events_OnLButtonDownEventHandler(sgWorld_OnLButtonDown);
            sgWorld.Window.SetInputMode(MouseInputMode.MI_FREE_FLIGHT);
            return true;
        }

        private void GenerateList(IFeature61 selectedFeature)
        {
            IFeatureAttributes61 attrs = selectedFeature.FeatureAttributes;
            int CRCode = Int32.Parse(attrs.GetFeatureAttribute("CRCode").Value);
            int FloorNo = Int32.Parse(attrs.GetFeatureAttribute("FloorNo").Value);
            double High = Double.Parse(attrs.GetFeatureAttribute("Zval").Value);

            listView1.Clear();
            listView1.View = View.Details;
            listView1.GridLines = true;//显示网格线
            listView1.Columns.Add("字 段", 100);
            listView1.Columns.Add("值", 100);

            ListViewItem nameItem = new ListViewItem("教室名称");//这个是第一行第一列
            nameItem.SubItems.Add("知明1-"+CRCode.ToString());//第一行第二列
            nameItem.UseItemStyleForSubItems = false;
            nameItem.BackColor = Color.DarkGray;

            ListViewItem highItem = new ListViewItem("楼层高度");
            highItem.SubItems.Add(High+" 米");
            highItem.UseItemStyleForSubItems = false;
            highItem.BackColor = Color.DarkGray;

            ListViewItem floorItem = new ListViewItem("楼层");//这个是第二行第一列
            floorItem.SubItems.Add("第"+FloorNo+"层");//第二行第二列
            floorItem.UseItemStyleForSubItems = false;
            floorItem.BackColor = Color.DarkGray;

            listView1.Items.Add(nameItem);//把第一行添加上
            listView1.Items.Add(highItem);//把第二行添加上
            listView1.Items.Add(floorItem);  
            //以下部分为数据库的内容
            CourseManager cm = new CourseManager();
            IList CrList = cm.GetCurrentClassRooms().GetKeyList();
            if (CrList.Contains(CRCode))
            {
                
                ListViewItem InfoItemn = new ListViewItem("当前上课信息");
                InfoItemn.UseItemStyleForSubItems = true;
                listView1.Items.Add(InfoItemn);

                DataTable dt = cm.GetCurrentCrByCode(CRCode);

                ListViewItem collegeItem = new ListViewItem("学院");//这个是第一行第一列
                collegeItem.SubItems.Add(dt.Rows[0]["College"].ToString());//第一行第二列
                collegeItem.UseItemStyleForSubItems = false;
                collegeItem.BackColor = Color.DarkGray;

                ListViewItem teacherItem = new ListViewItem("专业");//这个是第一行第一列
                teacherItem.SubItems.Add(dt.Rows[0]["MajorName"].ToString());//第一行第二列
                teacherItem.UseItemStyleForSubItems = false;
                teacherItem.BackColor = Color.DarkGray;

                ListViewItem courseItem = new ListViewItem("课程");//这个是第一行第一列
                courseItem.SubItems.Add(dt.Rows[0]["CourseName"].ToString());//第一行第二列
                courseItem.UseItemStyleForSubItems = false;
                courseItem.BackColor = Color.DarkGray;
                
                ListViewItem stuCountItem = new ListViewItem("学生人数");//这个是第一行第一列
                stuCountItem.SubItems.Add(dt.Rows[0]["StuCount"].ToString());//第一行第二列
                stuCountItem.UseItemStyleForSubItems = false;
                stuCountItem.BackColor = Color.DarkGray;

                listView1.Items.Add(collegeItem);
                listView1.Items.Add(teacherItem);
                listView1.Items.Add(courseItem);
                listView1.Items.Add(stuCountItem);
            }
            else
            {
                ListViewItem InfoItemn = new ListViewItem("该教室暂时没有课程");
                InfoItemn.UseItemStyleForSubItems = true;
                listView1.Items.Add(InfoItemn);
            }


        }
    }
}
